<template>
  <vxe-modal :title="title" v-model="visible" @close="close()" width="900px" :position="{ top: 100 }">
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top" inline :disabled="type == 'detail'">
      <el-form-item label="评论内容" prop="content">
        <el-input v-model="form.content" placeholder="请输入评论内容" maxlength="100" show-word-limit type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div v-if="type != 'detail'">
        <el-button @click="close()">关闭</el-button>
        <el-button type="primary" @click="submit()">确定</el-button>
      </div>
    </template>
  </vxe-modal>
</template>

<script lang="ts" setup>
import { ref, defineExpose, reactive, defineProps, defineEmits } from "vue"
import { commonRules } from "@/utils/validate"
import { ElMessage } from "element-plus"
import { getInfoById, editArticleComment } from "@/api/articleManage/comment"
import Editor from "@/components/Editor/index.vue"

import { Type, Id, Form } from "./type"

let type = ref<Type>("add")
const title = ref("")
const visible = ref(false)
const emits = defineEmits(["refreshList"])
const props = defineProps<{
  options: any
}>()

const formRef = ref()
const form = reactive(setDefaultForm())
const rules = reactive({
  content: commonRules.requiredInput
})

function setDefaultForm(): Form {
  return {
    content: "",
    comment_id: ""
  }
}

function submit() {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return
    // const api = type.value == "add" ? addArticle : editArticleComment
    const api = editArticleComment
    api(form).then(() => {
      ElMessage.success("操作成功")
      close()
      emits("refreshList")
    })
  })
}

function close() {
  visible.value = false
  Object.assign(form, setDefaultForm())
  formRef.value.resetFields()
}

function open({ type: t, comment_id }: { type: Type; comment_id?: Id }) {
  type.value = t
  form.comment_id = comment_id
  title.value = { add: "新增", edit: "编辑", detail: "详情" }[type.value]

  getInfo()
  visible.value = true
}

function getInfo() {
  getInfoById({ comment_id: form.comment_id }).then((res) => {
    Object.assign(form, res.data)
  })
}

defineExpose({ close, open })
</script>

<style lang="scss" scoped>
@import "@/styles/mixins.scss";

.el-form {
  @include grid-container($columns: 1, $non-grid-item-selector: ".editor");
}
</style>
